package com.example.demo1.controller;


import com.example.demo1.bean.PhoneNumber;
import com.example.demo1.service.serviceimpl.PhoneNumberServiceImpl;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

@Component
@RestController
public class DemoMainRestController {
    @Autowired
    PhoneNumberServiceImpl pnsi;

    @PostMapping("/uploadExcl")
    public String uploadExcel(MultipartFile[] uploadFiles, HttpServletRequest req) throws IOException {
        //设置上传文件的保存路径为项目运行目录下的uploadFile文件夹
        String path = req.getSession().getServletContext().getRealPath("/");
        System.out.println("存放路径"+path);

        InputStream inputStream = null;
        FileOutputStream fileOut = null;

        int count = 0;
        //错误文件
        String mistakenName = "";
        for (int i = 0; i < uploadFiles.length; i++) {
            String name = uploadFiles[i].getOriginalFilename();
            String[] split = name.split("\\.");
            //根据文件后缀（xls/xlsx）进行判断
            if ("xls".equals(split[1])) {
                continue;
            } else if ("xlsx".equals(split[1])) {
                continue;
            } else {
                System.out.println("文件类型错误! 文件名称 : "+name);
                count++;
                mistakenName+="文件类型错误! 文件名称 : "+name+"\n";
            }
        }
        if(count==uploadFiles.length){
            return "文件类型全部错误";
        }
        Workbook wb = null;
        for (int i = 0; i < uploadFiles.length; i++) {

            String name = uploadFiles[i].getOriginalFilename();
            //文件输出位置
            String outPath = URLDecoder.decode( path+name, "UTF-8");
            String[] split = name.split("\\.");
            //输入流
            inputStream = uploadFiles[i].getInputStream();

            System.out.println("文件地址"+outPath);
            fileOut = new FileOutputStream(outPath);

            //将文件保存到指定路径中
            IOUtils.copy(inputStream, fileOut);
            File excel = new File(outPath);
            try {
                //根据文件后缀（xls/xlsx）进行判断
                if ("xls".equals(split[1])) {
                    FileInputStream fis = new FileInputStream(excel);   //文件流对象
                    wb = new HSSFWorkbook(fis);
                } else if ("xlsx".equals(split[1])) {
                    wb = new XSSFWorkbook(excel);
                } else {
                    continue;
                }
            }catch (InvalidFormatException e) {
                e.printStackTrace();
            }

            ArrayList<PhoneNumber> list = getExcelMsg(outPath,wb);
            if(list.size()!=0){
                pnsi.addExcelMsg(list);
            }
            //获取文件
            File file = new File(outPath);
            //判断文件是否存在
            if(file.exists()){
                //存在则删除文件
                file.delete();
                System.out.println("删除成功");
            }
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (fileOut != null) {
                    fileOut.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return "保存数据完成\n"+mistakenName;
    }

    //读取Excel文件内容
    public ArrayList<PhoneNumber> getExcelMsg(String path,Workbook wb){
        ArrayList<PhoneNumber> list = new ArrayList<>();
        try {
            //获取文件
            File excel = new File(path);
            //判断文件是否存在
            if (excel.isFile() && excel.exists()) {
                //.是特殊字符，需要转义
                String[] split = excel.getName().split("\\.");

                //根据文件后缀（xls/xlsx）进行判断
                if ("xls".equals(split[1])) {
                    FileInputStream fis = new FileInputStream(excel);   //文件流对象
                    wb = new HSSFWorkbook(fis);
                } else if ("xlsx".equals(split[1])) {
                    wb = new XSSFWorkbook(excel);
                } else {
                    System.out.println("文件类型错误!");
                    return null;
                }
                //开始解析
                Sheet sheet = wb.getSheetAt(0);
                //第一行是列名，所以不读
                int firstRowIndex = sheet.getFirstRowNum() + 1;
                int lastRowIndex = sheet.getLastRowNum();
                System.out.println("firstRowIndex: " + firstRowIndex);
                System.out.println("lastRowIndex: " + lastRowIndex);
                if(lastRowIndex!=0){
                    //用于判断两个字段是否都为空
                    Boolean flag = false;
                    for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {   //遍历行
                        Row row = sheet.getRow(rIndex);
                        if (row != null) {
                            Cell cell = row.getCell(1);
                            cell.setCellType(cell.CELL_TYPE_STRING);//去除数字中的小数点
                            //判断手机号码是否为空字符串
                            if (!cell.toString().equals("")) {
                                PhoneNumber pn = new PhoneNumber(row.getCell(1).toString());
                                list.add(pn);
                            }
                        }
                    }
                }
            }else{
                System.out.println("找不到指定文件");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}
